#todo \
# 双层模式

class mylist(object):

    def __init__(self,n):
        self.List=[]
        self.n=n

    def add(self):
        for i in range(1,self.n):
            self.List.append(i)

    def __iter__(self):
        myiterator = myitems(self) #参数，此self代表mylist类的全部属性
        return myiterator
    def run(self):
        self.add()




class myitems(object):
    def __init__(self,my):#my接收mylist的全部属性
        self.sorce=1
        self.mylist=my

    def __next__(self):
        if self.sorce<len(self.mylist.List):
            print(f'第{self.sorce}')
            i=self.mylist.List[self.sorce-1]
            self.sorce += 1
            return i
        else:
            raise StopIteration

    def __iter__(self):
        return self

if __name__ == '__main__':
    wo=mylist(11)
    wo.run()
    for i in wo:
        print(i)




#todo \
# 单层模式

class myitems(object):
    def __init__(self,n):#my接收mylist的全部属性
        self.List = []
        self.n = n
        self.sorce=1


    def add(self):
        for i in range(1,self.n):
            self.List.append(i)

    def run(self):
        self.add()

    def __next__(self):
        if self.sorce<len(self.List):
            print(f'第{self.sorce}')
            i=self.List[self.sorce-1]
            self.sorce += 1
            return i
        else:
            raise StopIteration

    def __iter__(self):
        return self

if __name__ == '__main__':
    wo=myitems(11)
    wo.run()
    for i in wo:
        print(i)



"""斐波那契数列迭代器"""
class FibIterator(object):

    def __init__(self, n):
        """
        :param n: int, 指明生成数列的前n个数
        """
        self.n = n
        # current用来保存当前生成到数列中的第几个数了
        self.current = 0
        # num1用来保存前前一个数，初始值为数列中的第一个数0
        self.num1 = 0
        # num2用来保存前一个数，初始值为数列中的第二个数1
        self.num2 = 1

    def __next__(self):
        """被next()函数调用来获取下一个数"""
        if self.current < self.n:
            self.num1, self.num2 = self.num2, self.num1+self.num2
            self.current += 1
            return self.num1
        else:
            raise StopIteration

    def __iter__(self):
        """迭代器的__iter__返回自身即可"""
        return self


if __name__ == '__main__':
    fib = FibIterator(10)
    for num in fib:
        print(num, end=" ")



# from collections import Iterable
#
# isinstance([], Iterable)
# True
